package dao;

import entity.Member;
import entity.MemberGroup;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;

import java.util.List;

/**
 * Created by jifeng on 2016/12/2 0002.
 */
public class MemberDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private Session getCurrentSession() {
      return sessionFactory.getCurrentSession();
  }

    public void addMember(Member member) {
        getCurrentSession().save(member);
    }

    public  void updateMember(Member member){
    String sql ="update Member set integral = "+member.getIntegral()+" where id = "+member.getId()+"";
    getCurrentSession().createSQLQuery(sql).executeUpdate();
    }
    public Member findMemberById(int id){
        Member member = (Member)getCurrentSession().get(Member.class,id);
        return member;
    }

    public List<MemberGroup> findMemberGroupList(){
        List<MemberGroup> memberGroup =null;
        String sql ="select * from MemberGroup";
        SQLQuery query = getCurrentSession().createSQLQuery(sql);
        query.addScalar("id", StandardBasicTypes.INTEGER);
        query.addScalar("start",StandardBasicTypes.LONG);
        query.addScalar("end",StandardBasicTypes.LONG);
        query.addScalar("memberLevel",StandardBasicTypes.STRING);
        query.setResultTransformer(Transformers.aliasToBean(MemberGroup.class));
        memberGroup = query.list();
        return memberGroup;
    }

    public void deleteMemberGroup(int id){
        MemberGroup memberGroup =(MemberGroup)getCurrentSession().get(MemberGroup.class,id);
        if (memberGroup !=null){
            getCurrentSession().delete(memberGroup);
        }
    }

    public void addMemberGroup(MemberGroup memberGroup){
        getCurrentSession().save(memberGroup);
    }

    public void updateMemberU(int id,String level){
        Member member = findMemberByUserId(id);
        getCurrentSession().createSQLQuery("UPDATE member m SET m.level ='"+level+"' WHERE m.id="+member.getId()+"").executeUpdate();

    }

    public Member findMemberByUserId(int id){
        List<Member> memberList = getCurrentSession().createSQLQuery("SELECT * FROM member m WHERE m.userId ="+id+"").addEntity(Member.class).list();
        return memberList.get(0);
    }
}
